//
//  WithdrawalsVC.m
//  MRBang
//
//  Created by 铅笔 on 16/4/20.
//  Copyright © 2016年 杭州易网新科技. All rights reserved.
//

#import "WithdrawalsVC.h"

#import "MyBankCardVC.h"

#define CELLHEIGHT 125*PROPORTION_WIDTH

@interface WithdrawalsVC ()<UITableViewDataSource,UITableViewDelegate,withDrawCashChoseMybankCardDelegate,UITextFieldDelegate>
{
    UILabel *label_nameBank;
    NSString *str_bankNum;//银行卡卡号
}

@property (nonatomic,strong) UITableView *tableView_Recharge;

@property (nonatomic,strong) UITextField *textField_price;
@property (nonatomic,strong) UITextField *textField_pwd;


@end

@implementation WithdrawalsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"提现";
    
    self.view.backgroundColor = COLOR_EVERYVIEWBG;
    
    [self initWithDetailTableViewSubviews];
}


#pragma mark --- 创建明细表
- (void) initWithDetailTableViewSubviews
{
    self.tableView_Recharge = [[UITableView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth,170*PROPORTION_WIDTH+CELLHEIGHT*4)];
    [self.view addSubview:self.tableView_Recharge];
    self.tableView_Recharge.dataSource = self;
    self.tableView_Recharge.delegate = self;
    self.tableView_Recharge.showsVerticalScrollIndicator = NO;
    self.tableView_Recharge.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView_Recharge.scrollEnabled = NO;
    self.tableView_Recharge.backgroundColor = COLOR_EVERYVIEWBG;
    
    //button  recharge
    UIButton *button_recharge = [[UIButton alloc] initWithFrame:CGRectMake(30*PROPORTION_WIDTH,self.tableView_Recharge.bottom+55*PROPORTION_WIDTH, kScreenWidth-30*2*PROPORTION_WIDTH, 95*PROPORTION_WIDTH)];
    [self.view addSubview:button_recharge];
    [button_recharge setImage:[UIImage imageNamed:@"button_sureWithDraw"] forState:UIControlStateNormal];
    [button_recharge addTarget:self action:@selector(rechargeAndWithdrawsAction) forControlEvents:UIControlEventTouchUpInside];
    
}

//确认提现
- (void) rechargeAndWithdrawsAction
{
    [self DataSourceRequestCheck];
}

#pragma mark --- UITableViewDataSource
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellMyTradingRecordID = @"cellMyTradingRecordID";
    UITableViewCell *cell_recharge = [tableView cellForRowAtIndexPath:indexPath];
    if (cell_recharge == nil) {
        cell_recharge = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellMyTradingRecordID];
    }
    
    cell_recharge.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //label
    UILabel *label_leftTitle = [[UILabel alloc] init];
    [cell_recharge.contentView addSubview:label_leftTitle];
    label_leftTitle.font = [UIFont systemFontOfSize:24*PROPORTION_WIDTH];
    label_leftTitle.textColor = [BaseViewController colorWithHexString:@"#384056"];
    
    if (indexPath.row==1) {
        
        UIView *view_line = [[UIView alloc] initWithFrame:CGRectMake(27*PROPORTION_WIDTH, CELLHEIGHT-1, kScreenWidth, 1.0)];
        [cell_recharge.contentView addSubview:view_line];
        view_line.backgroundColor = [BaseViewController colorWithHexString:@"#EEEFF1"];
        
        label_leftTitle.frame = CGRectMake(44*PROPORTION_WIDTH, 50*PROPORTION_WIDTH, 130*PROPORTION_WIDTH, 31*PROPORTION_WIDTH);
        label_leftTitle.text = @"选择银行卡";
        //button
        UIButton *button_rightArrow = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-50*PROPORTION_WIDTH, 47*PROPORTION_WIDTH, 30*PROPORTION_WIDTH, 34*PROPORTION_WIDTH)];
        [cell_recharge.contentView addSubview:button_rightArrow];
        [button_rightArrow setImage:[UIImage imageNamed:@"return_right"] forState:UIControlStateNormal];
        
    }
    if (indexPath.row==0) {
        label_leftTitle.frame = CGRectMake(44*PROPORTION_WIDTH, 64*PROPORTION_WIDTH, kScreenWidth-44*PROPORTION_WIDTH*2, 22*PROPORTION_WIDTH);
        label_leftTitle.text = [NSString stringWithFormat:@"可提现金额   %@",self.str_balance];
        
        //右侧 文字 bottom
        UILabel *label_rightContentBottom = [[UILabel alloc] initWithFrame:CGRectMake(label_leftTitle.x, label_leftTitle.bottom+16*PROPORTION_WIDTH,330*PROPORTION_WIDTH, 21*PROPORTION_WIDTH)];
        [cell_recharge.contentView addSubview:label_rightContentBottom];
        label_rightContentBottom.font = [UIFont systemFontOfSize:Font_SIZE_24];
        label_rightContentBottom.text = @"（提现金额不能少于100元）";
        label_rightContentBottom.textColor = [BaseViewController colorWithHexString:@"#e8482e"];
        
        //line
        UIView *view_line = [[UIView alloc] initWithFrame:CGRectMake(0, 150*PROPORTION_WIDTH, kScreenWidth, 20*PROPORTION_WIDTH)];
        [cell_recharge.contentView addSubview:view_line];
        view_line.backgroundColor = [BaseViewController colorWithHexString:@"#EEEFF1"];
        
    }
    if (indexPath.row==1) {
        //label
        label_nameBank = [[UILabel alloc] init];
        [cell_recharge.contentView addSubview:label_nameBank];
        label_nameBank.font = [UIFont systemFontOfSize:24*PROPORTION_WIDTH];
        label_nameBank.textColor = [BaseViewController colorWithHexString:@"#384056"];
        label_nameBank.frame = CGRectMake(30*PROPORTION_WIDTH+label_leftTitle.right, 50*PROPORTION_WIDTH, 230*PROPORTION_WIDTH, 31*PROPORTION_WIDTH);
    }
    if (indexPath.row==2) {
        
        UIView *view_line = [[UIView alloc] initWithFrame:CGRectMake(27*PROPORTION_WIDTH, CELLHEIGHT-1, kScreenWidth, 1.0)];
        [cell_recharge.contentView addSubview:view_line];
        view_line.backgroundColor = [BaseViewController colorWithHexString:@"#EEEFF1"];
        
        label_leftTitle.frame = CGRectMake(44*PROPORTION_WIDTH, 50*PROPORTION_WIDTH, 58*PROPORTION_WIDTH, 39*PROPORTION_WIDTH);
        label_leftTitle.text = @"金额";
        
        //textfield
        self.textField_price = [[UITextField alloc] initWithFrame:CGRectMake(label_leftTitle.right+35*PROPORTION_WIDTH, label_leftTitle.y, 550*PROPORTION_WIDTH, label_leftTitle.height)];
        [cell_recharge.contentView addSubview:self.textField_price];
        self.textField_price.placeholder = @"请输入提现金额";
        self.textField_price.font = [UIFont systemFontOfSize:24*PROPORTION_WIDTH];
        self.textField_price.keyboardType = UIKeyboardTypeNumberPad;
        self.textField_price.delegate = self;
        self.textField_price.tag = 1100;
        [self.textField_price addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    if (indexPath.row==3) {
        
        label_leftTitle.frame = CGRectMake(44*PROPORTION_WIDTH, 50*PROPORTION_WIDTH, 58*PROPORTION_WIDTH, 39*PROPORTION_WIDTH);
        label_leftTitle.text = @"密码";
        
        //textfield
        self.textField_pwd = [[UITextField alloc] initWithFrame:CGRectMake(label_leftTitle.right+35*PROPORTION_WIDTH, label_leftTitle.y, 550*PROPORTION_WIDTH, label_leftTitle.height)];
        [cell_recharge.contentView addSubview:self.textField_pwd];
        self.textField_pwd.placeholder = @"请输入交易密码";
        self.textField_pwd.font = [UIFont systemFontOfSize:24*PROPORTION_WIDTH];
        self.textField_pwd.keyboardType = UIKeyboardTypeNumberPad;
        self.textField_pwd.delegate = self;
        self.textField_pwd.tag = 1101;
        self.textField_pwd.secureTextEntry = YES;
        [self.textField_pwd addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    
    return cell_recharge;
    
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.row==1) {
        MyBankCardVC *myCardView = [[MyBankCardVC alloc] init];
        myCardView.fromWhere = @"withdrawcash";
        myCardView.dalegateWithDraw = self;
        [self.navigationController pushViewController:myCardView animated:NO];
    }
//    else
//    {
        //添加手势
//        UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(commentTableViewTouchInSide)];
//        [self.tableView_Recharge addGestureRecognizer:tableViewGesture];
        [self commentTableViewTouchInSide];
    
//    }
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return 170*PROPORTION_WIDTH;
    }
    else
    {
        return CELLHEIGHT;
    }
}

#pragma mark -- withDrawCashChoseMybankCardDelegate
- (void) withDrawCashChoseMybankCard:(MyBankCardModel *)bankName
{
    label_nameBank.text = bankName.bankname;
    str_bankNum = bankName.banknum;
}

/**
 *键盘是否亮起
 */
- (void)textFieldDidChange:(UITextField *)textField
{
    switch (textField.tag) {
        case 1100:
            if (textField == self.textField_price) {
                if (textField.text.length>8) {
                    textField.text = [textField.text substringToIndex:9];
                }
            }
            
            break;
        case 1101:
            if (textField == self.textField_pwd) {
                if (textField.text.length>5) {
                    textField.text = [textField.text substringToIndex:6];
                }
            }
            
            break;
        default:
            break;
    }
}

#pragma mark  --- 点击tableView 收回键盘
- (void)commentTableViewTouchInSide{
    [self.textField_price resignFirstResponder];
    [self.textField_pwd resignFirstResponder];
}

- (void) touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark -- 网络数据请求
//提现  调用这个接口前先进行 验证码 验证

- (void) DataSourceRequestCheck
{
    [self commentTableViewTouchInSide];
    
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    
    if (![UIView NetFromStatus:status]) {
        NSLog(@"没有网络");
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [UIView showAlertMsg:@"网络连接已断开" andShowBgColor:[UIColor blackColor] andLabelTectColor:[UIColor whiteColor]];
        
        return;
    }
    else
    {
        NSString *strUrl = [NSString stringWithFormat:@"%@member/paypassword/check",MRAPI];
        NSDictionary *paras_loan = @{@"memberid":[[NSUserDefaults standardUserDefaults] objectForKey:@"memberid"],@"paypassword":self.textField_pwd.text};
        
        [[HttpRequest shardWebUtil] postNetworkRequestURLString:strUrl parameters:paras_loan success:^(id obj) {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
            NSLog(@"member/withdrawcashadd%@",obj);
            
            NSString *str_false = obj[@"error"];
            
            if (str_false.length==0) {
                
                //提交申请
                [self DataSourceRequestWithdrawalsVCView];
            }
            else
            {
                [BaseViewController showMessage:str_false];
            }
            
        } fail:^(NSError *error) {
            NSLog(@"get%@",error);
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [UIView showAlertMsg:@"网络请求超时"];
            
        }];
        
    }
}

#warning 这里是存在问题的 提现
- (void) DataSourceRequestWithdrawalsVCView
{
    if (self.textField_pwd.text.length<6 || self.textField_price.text.length==0|| label_nameBank.text.length==0) {
        [UIView showAlertMsg:@"请完善信息"];
        return;
    }
    
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    
    if (![UIView NetFromStatus:status]) {
        NSLog(@"没有网络");
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [UIView showAlertMsg:@"网络连接已断开" andShowBgColor:[UIColor blackColor] andLabelTectColor:[UIColor whiteColor]];
        
        return;
    }
    else
    {
        NSString *strUrl = [NSString stringWithFormat:@"%@member/withdrawcashadd",MRAPI];
        NSDictionary *paras_loan = @{@"memberid":[[NSUserDefaults standardUserDefaults] objectForKey:@"memberid"],@"amount":self.textField_price.text,@"bankname":label_nameBank.text,@"bankcrad":str_bankNum};
        
        [[HttpRequest shardWebUtil] postNetworkRequestURLString:strUrl parameters:paras_loan success:^(id obj) {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
//            NSLog(@"member/withdrawcashadd%@",obj);
            
            NSString *str_false = obj[@"error"];
            
            if (str_false.length==0) {
               
                [UIView showAlertMsg:@"提交成功，请耐心等待审核"];
                [self.navigationController popViewControllerAnimated:YES];
            }
            else
            {
                [BaseViewController showMessage:str_false];
            }
            
        } fail:^(NSError *error) {
            NSLog(@"get%@",error);
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [UIView showAlertMsg:@"网络请求超时"];
            
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
